package gdufs.lkl.calculator;

import java.io.Serializable;
import java.util.List;

public class CustomFunction implements Serializable {
    private long id;
    private String name;
    private List<String> parameters;
    private String expression;

    public CustomFunction(String name, List<String> parameters, String expression) {
        this.id = System.currentTimeMillis(); // Use timestamp as a simple unique ID
        this.name = name;
        this.parameters = parameters;
        this.expression = expression;
    }

    // Getters and Setters
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getParameters() {
        return parameters;
    }

    public void setParameters(List<String> parameters) {
        this.parameters = parameters;
    }

    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }

    public String getParametersAsString() {
        if (parameters == null || parameters.isEmpty()) {
            return "";
        }
        return String.join(", ", parameters);
    }
    
    /**
     * 计算函数值
     * @param paramValues 参数值列表，顺序与函数定义的参数列表相同
     * @return 计算结果
     * @throws Exception 如果计算过程中发生错误
     */
    public double calculate(List<Double> paramValues) throws Exception {
        if (parameters == null || paramValues == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        if (parameters.size() != paramValues.size()) {
            throw new IllegalArgumentException("参数数量不匹配");
        }
        
        // 替换表达式中的参数
        String expr = expression;
        for (int i = 0; i < parameters.size(); i++) {
            expr = expr.replace(parameters.get(i), String.valueOf(paramValues.get(i)));
        }
        
        // 使用自定义表达式计算器计算结果
        return ExpressionEvaluator.evaluate(expr);
    }
}
